package http

import (
	"context"
	"github.com/gin-gonic/gin"
	"io/ioutil"
)

// http/push中的代码将http请求中的参数提取出来，调用logic/push中的代码

func (s *Server) pushKeys(c *gin.Context) {
	var arg struct {
		Op   int32    `form:"operation"`
		Keys []string `form:"keys"`
		From int64    `form:"from"`
	}
	if err := c.BindQuery(&arg); err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	// request body的全部即是msg
	msg, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	if err = s.logic.PushKeys(context.TODO(), arg.Op, arg.Keys, msg, arg.From); err != nil {
		result(c, nil, RequestErr)
		return
	}
	result(c, nil, OK)
}

func (s *Server) pushMids(c *gin.Context) {
	var arg struct {
		Op   int32   `form:"operation"`
		Mids []int64 `form:"mids"`
		From int64   `form:"from"`
	}
	if err := c.BindQuery(&arg); err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	// read message
	msg, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	if err = s.logic.PushMids(context.Background(), arg.Op, arg.Mids, msg, arg.From); err != nil {
		errors(c, ServerErr, err.Error())
		return
	}
	result(c, nil, OK)
}

func (s *Server) pushRoom(c *gin.Context) {
	var arg struct {
		Op   int32  `form:"operation" binding:"required"`
		Type string `form:"type" binding:"required"`
		Room string `form:"room" binding:"required"`
		From int64  `form:"from"`
	}
	if err := c.BindQuery(&arg); err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	// read message
	msg, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	if err = s.logic.PushRoom(c, arg.Op, arg.Type, arg.Room, msg, arg.From); err != nil {
		errors(c, ServerErr, err.Error())
		return
	}
	result(c, nil, OK)
}

func (s *Server) pushAll(c *gin.Context) {
	var arg struct {
		Op int32 `form:"operation" binding:"required"`
	}
	if err := c.BindQuery(&arg); err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	msg, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errors(c, RequestErr, err.Error())
		return
	}
	if err = s.logic.PushAll(c, arg.Op, msg); err != nil {
		errors(c, ServerErr, err.Error())
		return
	}
	result(c, nil, OK)
}

func (s *Server) applyFriendReq(c *gin.Context) {

}

func (s *Server) replyFriendReq(c *gin.Context) {

}

func (s *Server) deleteFriend(c *gin.Context) {

}

func (s *Server) joinRoom(c *gin.Context) {

}

func (s *Server) quitRoom(c *gin.Context) {

}

// 客户端调用这个接口表示自己已经接收到某条信息
// 服务端收到ack后：
// - 将ack存储在kafka
// - 将这条消息在存储层中标记为received
// 由job将ack作为一条特殊的信息发送给comet
func (s *Server) messageReceived(c *gin.Context) {

}

// 客户端调用这个接口来同步自己还没有接收到的信息
// logic收到请求后，读取存储层把这些信息打入kafka
// job层将kafka中的信息再发送给comet
func (s *Server) syncMessage(c *gin.Context) {

}
